package com.tanhua.dubbo.api.impl;

import com.tanhua.domain.mongo.Visitors;
import com.tanhua.dubbo.api.VisitorsApi;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class VisitorsApiImpl implements VisitorsApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    // db.visitors.find({userId:1}).sort({date:-1}).limit(5)
    public List<Visitors> queryVisitors(Long userId, int count) {
        // 创建查询对象
        Query query = new Query(Criteria.where("userId").is(userId));
        // 指定排序参数
        query.with(Sort.by(Sort.Order.desc("date")));
        // 指定显示几条
        query.limit(count);

        List<Visitors> visitorsList = mongoTemplate.find(query, Visitors.class);
        return visitorsList;
    }

    @Override
    // db.visitors.find({userId:1, date: {$gt: 1614770370689}}).sort({date:-1})
    public List<Visitors> queryVisitors(Long userId, Long lastTime) {
        // 创建查询对象
        Query query = new Query(Criteria.where("userId").is(userId).and("date").gt(lastTime));
        // 指定排序参数
        query.with(Sort.by(Sort.Order.desc("date")));
        // 指定显示几条
        query.limit(5);

        List<Visitors> visitorsList = mongoTemplate.find(query, Visitors.class);
        return visitorsList;
    }
}
